import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueDevTools from "vite-plugin-vue-devtools";
import postcssPresetEnv from "postcss-preset-env";
import Inspect from "vite-plugin-inspect";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import browserslist from "browserslist";
import legacy from "@vitejs/plugin-legacy";
import { ArcoResolver } from "unplugin-vue-components/resolvers"; //按需引入组件
import { vitePluginForArco } from "@arco-plugins/vite-vue";

// 浏览器版本配置
const browserslistConfig = browserslist.loadConfig({ path: "." });

export default defineConfig({
  define: {
    __APP_ENV__: JSON.stringify(process.env.NODE_ENV),
    __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
    __BUILD_TIME__: JSON.stringify(new Date().toLocaleString())
  },
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ArcoResolver()]
    }),
    Components({
      resolvers: [
        ArcoResolver({
          sideEffect: true
        })
      ]
    }),
    vitePluginForArco({
      style: "css"
    }),

    legacy({
      targets: browserslistConfig, //需要兼容的目标列表，可以设置多个
      additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
      renderLegacyChunks: true,
      polyfills: [
        "es.symbol",
        "es.array.filter",
        "es.promise",
        "es.promise.finally",
        "es/map",
        "es/set",
        "es.array.for-each",
        "es.object.define-properties",
        "es.object.define-property",
        "es.object.get-own-property-descriptor",
        "es.object.get-own-property-descriptors",
        "es.object.keys",
        "es.object.to-string",
        "web.dom-collections.for-each",
        "esnext.global-this",
        "esnext.string.match-all"
      ]
    }),
    vueDevTools(),
    Inspect()
  ],
  resolve: {
    alias: [
      {
        find: "@",
        replacement: fileURLToPath(new URL("./src", import.meta.url))
      },
      {
        find: "vue",
        replacement: "vue/dist/vue.esm-bundler.js" // 需要编译tmp
      }
    ]
  },
  css: {
    postcss: {
      plugins: [postcssPresetEnv()]
    },
    preprocessorOptions: {
      less: {
        additionalData: `@import "${fileURLToPath(
          new URL("./src/styles/variable.less", import.meta.url)
        )}";`,
        devSourcemap: true, //开启css 文件索引 可以查看代码
        charset: false
      }
    }
  },
  build: {
    //分包策略
    rollupOptions: {
      output: {
        entryFileNames: "js/[name]-[hash].js",
        chunkFileNames: "js/[name]-chunk-[hash].js",
        // assetFileNames: "css/[name]-[hash][extname]",
        assetFileNames(assetInfo) {
          const names = assetInfo.names;
          const name = names[0];
          if (name.endsWith(".css")) {
            return "css/[name]-[hash][extname]";
          }
          const imgExts = ["png", "jpg", "jpeg", "gif", "svg"];
          if (imgExts.some((ext) => name.endsWith(ext))) {
            return "imgs/[name]-[hash][extname]";
          }
          return "assets/[name]-[hash][extname]";
        },
        manualChunks: (id) => {
          if (id.includes("node_modules")) {
            if (id.includes("vue")) return "vue";
            if (id.includes("arco-design")) return "arco";
            return "vendor";
          }
        }
      }
    }
  },
  envPrefix: ["VITE_", "APP_"],
  base: "/admin/", //打包路径
  server: {
    // ← ← ← ← ← ←
    host: "0.0.0.0",
    // https : true,
    open: false,
    port: 5182
    // proxy: {
    //   "/apixxx": {
    //     target: "http://localhost:3000",
    //     changeOrigin: true,
    //     secure: false,
    //     rewrite: (path) => path.replace(/^\/apixxx/, "")
    //   }
    // }
  }
});
